package com.zhiyu.controller;

import com.github.pagehelper.PageInfo;
import com.zhiyu.common.ApiReturn;
import com.zhiyu.pojo.Admin;
import com.zhiyu.pojo.Orders;
import com.zhiyu.pojo.Products;
import com.zhiyu.pojo.User;
import com.zhiyu.service.AdminService;
import com.zhiyu.service.OrdersService;
import com.zhiyu.service.ProductsService;
import com.zhiyu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;

@RequestMapping("admin")
@Controller
@CrossOrigin
public class AdminController {
    @Autowired
    private AdminService adminService;


    //管理员登录
    @RequestMapping("login")
    @ResponseBody
    public ApiReturn login(Admin admin, HttpServletRequest request, HttpServletResponse response){
        String result = adminService.login(admin);
        if (result.equals("管理员不存在")){
            return ApiReturn.error("账号或者密码错误！");
        }
        //携带用户信息  result为： id:用户名
        request.getSession().setAttribute("adminInfo",result);
        return ApiReturn.success("返回管理员登录数据",result);
    }

    //管理员登录信息
    @RequestMapping("getAdminInfo")
    @ResponseBody
    public ApiReturn getAdminInfo(HttpServletRequest request, HttpServletResponse response){
        //获取session中的管理员信息
        String adminInfo = (String) request.getSession().getAttribute("adminInfo");
        if(adminInfo == null || adminInfo == ""){
            return ApiReturn.error("管理员未登录");
        }
        String[] adminStr = adminInfo.split(":");
        Admin admin = new Admin();
        admin.setId(Integer.valueOf(adminStr[0]));
        admin.setAdminName(adminStr[1]);
        return ApiReturn.success("返回管理员登录数据",admin);

    }

    //管理员退出登录
    @RequestMapping("logout")
    @ResponseBody
    public ApiReturn logout(HttpServletRequest request,HttpServletResponse response){
        //退出
        HttpSession httpSession = request.getSession();
        httpSession.removeAttribute("adminInfo");
        Cookie[] cookies = request.getCookies();
        if(cookies != null && cookies.length >0){
            for(Cookie c : cookies){
                if("autoLogin".equals(c.getName())){
                    //设置cookie存活时间为0
                    c.setMaxAge(0);
                    //将cookie响应到前台
                    response.addCookie(c);
                    break;
                }
            }
        }else{
            return ApiReturn.error("退出失败");
        }
        return ApiReturn.success("退出成功");
    }

}
